<template>
  <div>
    <el-dialog
      :title="node_id ? '编辑用户' : '添加用户'"
      :visible.sync="dialogVisible"
      width="60%"
      :before-close="handleClose"
      @open="open"
    >
      <el-form
        :model="Form_data"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="name">
          <el-input v-model="Form_data.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="name">
          <el-input v-model="Form_data.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="name">
          <el-input v-model="Form_data.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="name">
          <el-input v-model="Form_data.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submit_form">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
    node_id: {
      ty: String,
      default: '',
    },
  },
  data() {
    return {
      Form_data: {},
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' },
        ],
        email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
        mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
      },
    }
  },

  methods: {
    async open() {
      if (this.node_id === '') return
      await this.$axios.query_user_for_id(this.node_id).then((res) => {
        const { meta, data } = res
        if (meta?.status !== 200) return
        this.Form_data = data || {}
      })
    },
    //关闭
    handleClose() {
      this.Form_data = {}
      this.$refs.ruleForm.resetFields()
      this.$parent.getUserLits() //通知父组件更新列表
      this.$emit('update:dialogVisible', false)
    },
    //确定
    submit_form(formName) {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.$axios.add_user(this.Form_data).then((res) => {
            const { meta } = res
            if (meta?.status !== 201) return this.$message.error(meta?.msg)
            this.handleClose()
            this.$message.success(meta?.msg)
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
  },
}
</script>

<style>
</style>
